'''
Created on 2012-7-18

@author: xxy
'''

import math
import world_message

class Vector2(object):
    def __init__(self, position):
        self.x = position[0]
        self.y = position[1]
        
    def isToward(self, toward):
        v_point = None
        if toward == world_message.Toward.EAST:
            v_point = (10, 0)
        elif toward == world_message.Toward.NORTH:
            v_point = (0, -10)
        elif toward == world_message.Toward.NORTH_EAST:
            v_point = (10, -10)
        elif toward == world_message.Toward.NORTH_WEST:
            v_point = (-10, -10)
        elif toward == world_message.Toward.SOUTH:
            v_point = (0, 10)
        elif toward == world_message.Toward.SOUTH_EAST:
            v_point = (10, 10)
        elif toward == world_message.Toward.SOUTH_WEST:
            v_point = (-10, 10)
        elif toward == world_message.Toward.WEST:
            v_point = (-10, 0)
            
        if (v_point[0] * self.x + v_point[1] * self.y) >= 0:
            return True
        else:
            return False
               
            
    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)

    def getLength(self):
        return math.sqrt(self.x**2 + self.y**2)
    
    def toTuple(self):
        return (self.x, self.y)

    def getNormalized(self):
        magnitude = self.getLength()
        try:
            return Vector2((self.x / magnitude, self.y / magnitude))
        except  ZeroDivisionError:
            return Vector2((0, 0))

    def getDistance(self, destion):
        if type(destion) is tuple:
            destion = Vector2(destion)
        return math.sqrt((destion.x - self.x)**2 + (destion.y - self.y)**2)
    
    def isInArea(self, point, radius):
        if (self.getDistance(point) < radius):
            return True
        else:
            return False

    def __add__(self, rhs):
        return Vector2((self.x + rhs.x, self.y + rhs.y))

    def __sub__(self, rhs):
        return Vector2((self.x - rhs.x, self.y - rhs.y))

    def __mul__(self, scalar):
        return Vector2((self.x * scalar, self.y * scalar))

    def __div__(self, scalar):
        return Vector2((self.x / scalar, self.y / scalar))
